<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\System\Services;

use Modules\System\Models\Area;
use App\Support\Tree;

class AreaService {

	/**
	 * @title 区域列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getAreaList($request){
		$map = [];
		if($request->filled('title')){
			$map[] = ['title', 'like', '%' . $request->input('title') . '%'];
		}
		if($request->filled('id')){
			$map[] = ['id', '=', $request->input('id')];
		}
		if($request->filled('parent_code')){
			$map[] = ['parent_code', '=', $request->input('parent_code')];
		}

		$query = Area::where($map)->orderBy('id', 'asc');

		if($request->filled('page')){
			$data = [
				'total' => $query->count(),
				'page' => $request->input('page', 1),
				'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 10))->get(),
			];
		}else{
			if($request->filled('is_tree') && $request->filled('is_tree') == 1){
				$query = $query->get()->toArray();
				$tree = new Tree();
				$data = $tree->list_to_tree($query, 0, 'code', 'parent_code');
			}else{
				$data = $query->get();
			}
		}
		return $data;
	}

	/**
	 * @title 添加区域
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function create($request){
		$request->validate([
			'title' => 'required',
			'code' => 'required|unique:system_areas',
		], [
			'code.unique' => '编码已存在',
			'title.required' => '请输入标题',
			'code.required' => '请输入编码',
		]);

		$area = new Area;

		foreach ($area->setFilterFields($request->all()) as $key => $value) {
			$area->$key = $value;
		}

		$area->save();
		return $area;
	}

	/**
	 * @title 编辑区域
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request){
		$request->validate([
			'id' => 'required',
			'title' => 'required',
			'code' => 'required',
		], [
			'id.required' => '参数错误',
			'title.required' => '请输入标题',
			'code.required' => '请输入编码',
		]);

		$area = Area::where('id', '=', $request->input('id'))->first();

		foreach ($area->setFilterFields($request->all()) as $key => $value) {
			$area->$key = $value;
		}

		$area->save();
		return $area;
	}

	public function delete($request){
		$request->validate([
			'id' => 'required',
		], [
			'id.required' => '参数错误',
		]);

		$area = Area::where('id', '=', $request->input('id'))->first();
		$area->delete();
		return $area;
	}
}
